package com.example.personblog.repository;

import com.example.personblog.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

public interface UserRepository extends JpaRepository<User, Long> {
    
    /**
     * 根据用户名查找用户
     */
    User findByUsername(String username);
    
    /**
     * 检查用户名是否存在
     */
    boolean existsByUsername(String username);
    
    /**
     * 更新最后登录时间
     */
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.lastLoginTime = CURRENT_TIMESTAMP WHERE u.id = :userId")
    void updateLastLoginTime(@Param("userId") Long userId);
    
    /**
     * 更新用户状态
     */
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.status = :status WHERE u.id = :userId")
    void updateStatus(@Param("userId") Long userId, @Param("status") Integer status);
    
    /**
     * 更新用户头像
     */
    @Modifying
    @Transactional
    @Query("UPDATE User u SET u.avatar = :avatar WHERE u.id = :userId")
    void updateAvatar(@Param("userId") Long userId, @Param("avatar") String avatar);
    
    /**
     * 分页查询用户列表
     */
    Page<User> findByStatus(Integer status, Pageable pageable);
    
    /**
     * 搜索用户
     */
    @Query("SELECT u FROM User u WHERE u.status = 1 AND (u.username LIKE %:keyword% OR u.nickname LIKE %:keyword%)")
    Page<User> searchUsers(@Param("keyword") String keyword, Pageable pageable);
} 